package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Spoteng;
import cn.wolfcode.wolf2w.query.SpotengQueryObject;
import cn.wolfcode.wolf2w.repository.SpotengRepository;
import cn.wolfcode.wolf2w.service.ISpotengService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class SpotengServiceImpl implements ISpotengService {
    @Autowired
    private SpotengRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Spoteng spoteng) {
        spoteng.setId(null);//防止游标
        repository.save(spoteng);
    }

    @Override
    public void update(Spoteng spoteng) {
        repository.save(spoteng);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Spoteng get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Spoteng> list() {
        return repository.findAll();
    }

    @Override
    public Page<Spoteng> query(SpotengQueryObject qo) {
        //查询的条件对象
        Query query = new Query();
        //拼接条件
        long count = template.count(query, Spoteng.class);//计算一共有多少条数据 query 为无条件 totalCount  集合MOngoDb
        if (count == 0) {
            return Page.empty();//空的页面对象
        }
        //分页加排序---->条件拼接
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //把条件放入查询对象中
        query.with(pageRequest);
        //查询当前结果集template.find
        List<Spoteng> list = template.find(query, Spoteng.class);
        //PageImpl等价于之前的PageResult
        return new PageImpl<>(list, pageRequest, count);//PageResult原生的  pageRequest当前页  多少条数
        //PageHadler  分页插件的
    }

    @Override
    public Spoteng getBySprotiod(String id) {
        return repository.findBySprotiod(id);
    }
}